跳到主要内容

56 合并区间

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xv11yj/

cost: 13m49s

class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
std::sort(intervals.begin(), intervals.end(),
[](vector<int> a, vector<int> b) { return a[0] < b[0]; });
vector<vector<int>> res;
for (const auto interval : intervals) {
if (res.empty()) {
res.push_back(interval);
continue;
}
auto& back = res.back();
if (back[1] < interval[0]) {
res.push_back(interval);
} else {
back[1] = std::max(interval[1], back[1]);
}
}
return res;
}
};